package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 过滤器，统一全站编码，避免中文乱码的出现
 */
public class CharacterFilter implements Filter {
    public void init(FilterConfig filterConfig) {}
    public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain)throws IOException,ServletException{
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        // 拦截所有的请求，解决全站中文乱码
        // 指定request和response的编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 对request进行包装
        CharacterRequest characterRequest = new CharacterRequest(request);
        chain.doFilter(characterRequest,response);
    }
    public void destroy(){}
}
// 继承默认包装类HttpServletRequestWrapper
class CharacterRequest extends HttpServletRequestWrapper{
    public CharacterRequest(HttpServletRequest request){
        super(request);
    }
    // 重写getParameter()方法
    public String getParameter(String name){
        // 调用被包装对象的getParameter()方法，获得请求参数
        String value = super.getParameter(name);
        if (value==null){
            return null;
        }
        String method = super.getMethod();
        if("get".equalsIgnoreCase(method)){
            value = new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
        }
        // 解决乱码后返回结果
        return value;
    }
}